package com.anpxd.erpad.ui

import android.Manifest
import android.content.Intent
import android.os.SystemClock
import android.support.v7.app.AlertDialog
import android.view.View
import com.anpxd.ewalker.utils.replaceFragmentInActivity
import com.anpxd.ewalker.utils.toast
import kotlinx.android.synthetic.main.activity_main.*
import com.anpxd.baselibrary.utils.AppManager
import android.app.ActivityManager
import android.content.Context
import android.util.Log
import com.anpxd.erpad.service.JobWakeUpService
import android.os.Build
import com.anpxd.erpad.App
import com.anpxd.erpad.R
import com.anpxd.erpad.bean.BusTag
import com.anpxd.erpad.net.ApiFactory
import com.anpxd.erpad.service.GuardService
import com.anpxd.erpad.service.MessageService
import com.anpxd.erpad.utils.BackHomeTimer
import com.bumptech.glide.request.RequestOptions
import com.gg.baseproject.Composers
import com.gg.image.config.GlideApp
import com.lsxiao.apollo.core.Apollo
import com.lsxiao.apollo.core.annotations.Receive
import com.lsxiao.apollo.core.contract.ApolloBinder
import com.socks.library.KLog
import com.tencent.bugly.crashreport.CrashReport
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit


class MainActivity : BaseActivity() {

    override fun getLayoutRes(): Int = R.layout.activity_main

    lateinit var carListFragment: CarListFragment

    private lateinit var mBinder: ApolloBinder

    override fun initArguments() {

        BackHomeTimer.getInstance().startTimer()//开启定时器

        startService(Intent(this, MessageService::class.java))
        startService(Intent(this, GuardService::class.java))
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            startService(Intent(this, JobWakeUpService::class.java))
        }
    }

    override fun onDestroy() {
        super.onDestroy()

        if (this::mBinder.isInitialized) {
            mBinder.unbind()
        }
    }

    override fun initTitle() {

        if (!Apollo.isBind(this))
            mBinder = Apollo.bind(this)
    }

    override fun initView() {
        carListFragment = supportFragmentManager.findFragmentById(R.id.car_list) as CarListFragment?
                ?: CarListFragment.newInstance().also {
            replaceFragmentInActivity(it, R.id.car_list)
        }
        supportFragmentManager.findFragmentById(R.id.bannerFragment) as BannerFragment?
                ?: BannerFragment.newInstance().also {
            replaceFragmentInActivity(it, R.id.bannerFragment)
        }

        erp_logo.setOnClickListener(object : View.OnClickListener {
            val COUNTS = 10//点击次数
            val DURATION = (3 * 1000).toLong()//规定有效时间
            var mHits = LongArray(COUNTS)
            override fun onClick(v: View?) {
                /**
                 * 实现双击方法
                 * src 拷贝的源数组
                 * srcPos 从源数组的那个位置开始拷贝.
                 * dst 目标数组
                 * dstPos 从目标数组的那个位子开始写数据
                 * length 拷贝的元素的个数
                 */
                KLog.w("123123123", AppManager.getInstance().currentActivity())
                System.arraycopy(mHits, 1, mHits, 0, mHits.size - 1)
                //实现左移，然后最后一个位置更新距离开机的时间，如果最后一个时间和最开始时间小于DURATION，即连续5次点击
                mHits[mHits.size - 1] = SystemClock.uptimeMillis()
                if (mHits[0] >= SystemClock.uptimeMillis() - DURATION) {
                    AlertDialog.Builder(this@MainActivity)
                            .setMessage("是否退出登陆")
                            .setNegativeButton("我再想想", null)
                            .setPositiveButton("确认退出", { _, _ ->
                                App.instance.setUser("")
                                toast("退出成功")
                                startActivity(Intent(this@MainActivity, LoginActivity::class.java))
                                AppManager.getInstance().finishActivity()
                            })
                            .setCancelable(false)
                            .create().show()
                }
            }
        })
        qrcode.setOnClickListener(object : View.OnClickListener {
            val COUNTS = 10//点击次数
            val DURATION = (3 * 1000).toLong()//规定有效时间
            var mHits = LongArray(COUNTS)
            override fun onClick(v: View?) {
                /**
                 * 实现双击方法
                 * src 拷贝的源数组
                 * srcPos 从源数组的那个位置开始拷贝.
                 * dst 目标数组
                 * dstPos 从目标数组的那个位子开始写数据
                 * length 拷贝的元素的个数
                 */
                System.arraycopy(mHits, 1, mHits, 0, mHits.size - 1)
                //实现左移，然后最后一个位置更新距离开机的时间，如果最后一个时间和最开始时间小于DURATION，即连续5次点击
                mHits[mHits.size - 1] = SystemClock.uptimeMillis()
                if (mHits[0] >= SystemClock.uptimeMillis() - DURATION) {
                    AlertDialog.Builder(this@MainActivity)
                            .setMessage("是否退出程序")
                            .setNegativeButton("我再想想", null)
                            .setPositiveButton("确认退出", { _, _ ->
                                toast("退出成功")
                                AppManager.getInstance().finishAllActivity()
                                BackHomeTimer.getInstance().cancelTimer()
                            })
                            .setCancelable(false)
                            .create().show()
                }
            }
        })



        search.setOnClickListener {
            BackHomeTimer.getInstance().resetTime()
            Apollo.emit(BusTag.start)
        }
    }


    override fun initData() {
        val logo = App.instance.getImageUrl() + App.instance.getUser()?.marketLogo
        GlideApp.with(this).load(logo).skipMemoryCache(false).into(shop_logo)

        ApiFactory.getWxApi()
                .getIcon()
                .compose(Composers.handleError())
                .subscribe({
                    GlideApp.with(this).load(App.instance.getImageUrl() + it.wxQrCode).into(qr_code)
                    KLog.w("url", App.instance.getImageUrl() + it.wxQrCode)
                    CrashReport.postCatchedException(Throwable("shopLogo = $logo \r\n qrcode = ${App.instance.getImageUrl() + it.wxQrCode}"))
                }, {

                })
    }

    private var isCurrentRunningForeground = true

    override fun onStart() {
        super.onStart()
        if (!isCurrentRunningForeground) {
            Log.d("tag", ">>>>>>>>>>>>>>>>>>>切到前台 activity process")
        }
    }

    override fun onStop() {
        super.onStop()
        isCurrentRunningForeground = isRunningForeground()
//        if (!isCurrentRunningForeground) {
//            Log.d("tag", ">>>>>>>>>>>>>>>>>>>切到后台 activity process")
//            Observable.interval(60, TimeUnit.SECONDS)
//                    .subscribeOn(Schedulers.io())
//                    .observeOn(AndroidSchedulers.mainThread())
//                    .subscribe {
//                        KLog.w("time", it)
//                        startActivity(Intent(this, MainActivity::class.java))
//                    }
//        }
    }

    private fun isRunningForeground(): Boolean {
        val activityManager = this.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val appProcessInfos = activityManager.runningAppProcesses
        // 枚举进程
        for (appProcessInfo in appProcessInfos) {
            if (appProcessInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                if (appProcessInfo.processName == this.applicationInfo.processName) {
                    Log.d("tag", "EntryActivity isRunningForeGround")
                    return true
                }
            }
        }
        Log.d("tag", "EntryActivity isRunningBackGround")
        return false
    }

    @Receive(BusTag.reloadData)
    fun reloadData() {
        initData()
    }


}
